﻿using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace MainUI
{
    public partial class RegionSelectorWindow : Window
    {
        private Point _dragStart;
        private Rect _currentSelection;
        private DispatcherTimer _guideTimer;
        private DpiScale _dpi; // 存储DPI缩放信息

        public Rect SelectedRegion => _currentSelection;

        public RegionSelectorWindow()
        {
            InitializeComponent();
            InitializeInteractionSystem();
            // 绑定鼠标事件
            MouseDown += OnMouseDown;
            MouseMove += OnMouseMove;
            MouseUp += OnMouseUp;
            KeyDown += OnKeyDownHandler; // 绑定键盘事件
        }

        private void InitializeInteractionSystem()
        {
            // 初始化辅助线定时器
            _guideTimer = new DispatcherTimer
            {
                Interval = TimeSpan.FromMilliseconds(16) // ~60FPS
            };
            _guideTimer.Tick += UpdateGuidePosition;

            // 窗口加载完成后获取DPI信息
            Loaded += (sender, e) =>
            {
                _dpi = VisualTreeHelper.GetDpi(this); // 必须在此事件中获取
                Debug.WriteLine($"DPI缩放比例: {_dpi.DpiScaleX}x");

                // 初始化Thumb控件尺寸（物理像素）
                selectionThumb.Width = 10 / _dpi.DpiScaleX;
                selectionThumb.Height = 10 / _dpi.DpiScaleY;
            };
        }

        #region 鼠标事件处理
        private void OnMouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ChangedButton != MouseButton.Left) return;

            _dragStart = ToPhysicalPixels(e.GetPosition(this));
            selectionThumb.Visibility = Visibility.Visible;

            // 初始化选区位置
            Canvas.SetLeft(selectionThumb, _dragStart.X);
            Canvas.SetTop(selectionThumb, _dragStart.Y);
            selectionThumb.Width = 0;
            selectionThumb.Height = 0;

            CaptureMouse(); // 确保鼠标捕获
        }

        private void OnMouseMove(object sender, MouseEventArgs e)
        {
            if (e.LeftButton != MouseButtonState.Pressed) return;

            var currentPos = ToPhysicalPixels(e.GetPosition(this));
            UpdateSelectionVisual(currentPos);
            UpdateSizeLabel(currentPos);
        }

        private void OnMouseUp(object sender, MouseButtonEventArgs e)
        {
            ReleaseMouseCapture();
            _guideTimer.Stop();

            // 计算最终选区（物理像素）
            var endPos = ToPhysicalPixels(e.GetPosition(this));
            _currentSelection = new Rect(
                Math.Min(_dragStart.X, endPos.X),
                Math.Min(_dragStart.Y, endPos.Y),
                Math.Abs(endPos.X - _dragStart.X),
                Math.Abs(endPos.Y - _dragStart.Y)
            );

            DialogResult = true;
            Close();
        }
        #endregion

        #region 坐标转换与选区更新
        private Point ToPhysicalPixels(Point logicalPoint)
        {
            return new Point(
                logicalPoint.X * _dpi.DpiScaleX,
                logicalPoint.Y * _dpi.DpiScaleY
            );
        }

        private void UpdateSelectionVisual(Point currentPos)
        {
            // 计算选区尺寸（物理像素）
            double width = Math.Abs(currentPos.X - _dragStart.X);
            double height = Math.Abs(currentPos.Y - _dragStart.Y);

            // 约束边界（基于物理屏幕尺寸）
            double maxX = SystemParameters.PrimaryScreenWidth * _dpi.DpiScaleX - width;
            double maxY = SystemParameters.PrimaryScreenHeight * _dpi.DpiScaleY - height;
            double left = Math.Max(0, Math.Min(_dragStart.X, currentPos.X));
            double top = Math.Max(0, Math.Min(_dragStart.Y, currentPos.Y));

            // 更新Thumb位置
            Canvas.SetLeft(selectionThumb, left);
            Canvas.SetTop(selectionThumb, top);
            selectionThumb.Width = width;
            selectionThumb.Height = height;
        }

        private void UpdateSizeLabel(Point currentPos)
        {
            sizeLabel.Text = $"{selectionThumb.Width / _dpi.DpiScaleX:F0} × {selectionThumb.Height / _dpi.DpiScaleY:F0}";
            Canvas.SetLeft(sizeLabel, selectionThumb.Width + 20);
            Canvas.SetTop(sizeLabel, selectionThumb.Height + 20);
            sizeLabel.Visibility = Visibility.Visible;
        }
        #endregion

        #region 辅助功能
        private void UpdateGuidePosition(object sender, EventArgs e)
        {
            // 更新辅助线位置（逻辑坐标）
            leftGuide.X1 = leftGuide.X2 = Canvas.GetLeft(selectionThumb) / _dpi.DpiScaleX;
            topGuide.Y1 = topGuide.Y2 = Canvas.GetTop(selectionThumb) / _dpi.DpiScaleY;
        }

        private void OnWindowLoaded(object sender, RoutedEventArgs e)
        {
            // 捕获全屏尺寸
            var screenWidth = SystemParameters.PrimaryScreenWidth;
            var screenHeight = SystemParameters.PrimaryScreenHeight;
            dimmingLayer.Width = screenWidth;
            dimmingLayer.Height = screenHeight;

            // 调试输出验证
            Debug.WriteLine($"窗口已加载，屏幕尺寸: {screenWidth}x{screenHeight}");
        }
        private void OnKeyDownHandler(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Escape)
            {
                DialogResult = false;
                Close();
            }
        }
        #endregion
    }
}
